<?php
/**
 * Model for performing CRUD operations on companies database table.
 * @package backend-companies/models
 * @category Model
 * 
 * @author Mark Angelo Angulo
 * @copyright (c) 2015
 */
class Company_Model extends Crud {
    
    /**
     *  Constructor method.
     */
    function __construct()
    {
	parent::__construct();
        
        $cms = $this->cms;
        
        $this->table = $cms['db_prefix'] . 'companies';
        $this->primary_key = 'id';
    }
    
    /**
     * Change status to archived. Usually used for records that can't be deleted due to constraints
     * @param array $values Array of values to be deleted
     * @param int $column Databse column from where the values are checked
     * @return string Returns database errors if any
     */
    function archive($values = array(), $column = NULL)
    {
        $column = $column === NULL ? $this->primary_key : $column;
        
        if ( empty($values) )
        {
            return NULL;
        } else
        {
            $archived = array();
            
            foreach ($values as $value)
            {
                $this->db->where($column, $value);
                $this->db->delete($this->table);
                $error_msg = $this->db->_error_message();
                
                // if we cannot delete it, change it's status to archived
                if($error_msg)
                {
                    $this->db->where($column, $value);
                    $this->db->update($this->table, array('status' => 'archived'));
                    array_push($archived, $value);
                    continue;
                } else
                {
                    $delete_company = $this->one(array($column => $value))->get();
                    if(isset($delete_company) && ! empty($delete_company['image']))
                    {
                        unlink_file($delete_company['image'], $this->logo_path);
                    }
                }
            }
            return $archived;
        }
    }
    
    
    function teams()
    {
        $cms = $this->cms;
        return $this->has_many($cms['db_prefix'] . 'teams', 'company_id', 'id');
    }

}

/* End of file company_model.php */
/* Location: ./application/companies/backend-companies/models/company_model.php */